<template>
	<div class="pipeline-execution">
		<!-- v-hasPermi="[]" -->
		<el-table
			v-loading="loading"
			:data="list"
			row-key="id"
			@selection-change="handleSelectionChange"
		>
			<el-table-column
				type="selection"
				width="55"
				fixed="left"
			/>
			<el-table-column
				prop="id"
				align="center"
				label="执行id"
				width="90"
				show-overflow-tooltip
			/>
			<el-table-column
				prop="deployId"
				align="center"
				label="部署id"
				width="90"
				show-overflow-tooltip
			/>
			<el-table-column
				prop="deployType"
				label="部署类型"
				align="center"
				show-overflow-tooltip
			>
				<template #default="{ row }">
					{{ deployTypeOptions?.filter(item => item.value === row.deployType)?.[0]?.label ?? '-' }}
				</template>
			</el-table-column>
			<el-table-column
				prop="batchId"
				label="执行批次"
				align="center"
        width="150"
			/>

			<el-table-column
				label="tag"
				align="center"
				width="145"
			>
				<template #default="{ row }">
					<div
						v-for="(tagItem, index) in dataTransform(row?.data)"
						:key="index"
						class="tags-tag"
					>
						<el-tag style="margin-right: 5px; margin-bottom: 5px">
							{{ tagItem.tag }}
						</el-tag>
					</div>
				</template>
			</el-table-column>

			<el-table-column
				label="服务"
				width="120"
				align="center"
			>
				<template #default="{ row }">
					<div class="column-services">
						<el-popover
							v-for="(tagItem, tagIndex) in dataTransform(row?.data)"
							placement="right"
							title="服务列表"
							trigger="hover"
							:key="tagIndex"
						>
							<div
								class="popover-reference"
								slot="reference"
							>
								查看服务器
							</div>
							<div class="column-services-item">
								<div
									v-for="(service, serviceIndex) in tagItem.services"
									:key="serviceIndex"
								>
									<el-tag style="margin-right: 5px; margin-bottom: 5px">
										{{ service.name }}
									</el-tag>
								</div>
							</div>
						</el-popover>
					</div>
				</template>
			</el-table-column>

			<el-table-column
				label="环境"
				width="180"
				prop="env"
				align="center"
			/>
      <el-table-column
        label="请求数据"
        width="450"
        prop="requestData"
        align="center"
      />

			<el-table-column
				prop="creator"
				label="执行人"
        width="50"
				align="center"
			/>
			<el-table-column
				label="执行时间"
				width="180"
				prop="createTime"
				align="center"
			>
				<template v-slot="scope">
					<span>{{ parseTime(scope.row.createTime) }}</span>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			:page.sync="queryParams.pageNo"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>
	</div>
</template>

<script>
import { uniqBy } from 'lodash-es';
import { piplineExecPage } from '@/api/pipeline/pipeline-execution';

export default {
	name: 'pipelineExecution',
	props: {
		env: {
			type: String,
			default: '',
		},
		deployId: {
			type: String,
			default: '',
		},
		deployTypeOptions: {
			type: Array,
			defualt: () => {
				return [];
			},
		},
	},
	data() {
		return {
			obj: {},
			multipleSelection: [],
			envSelectValues: {},
			// 遮罩层
			loading: true,
			// 总条数
			total: 0,
			// 部署列表
			list: [],
			// 查询参数
			queryParams: {
				pageNo: 1,
				pageSize: 10,
			},
			timer: null,
		};
	},
	async created() {
		this.loading = false;
		this.getList();
	},
	methods: {
		dataTransform(data) {
			if (data) {
				return JSON.parse(data);
			}
			return null;
		},
		handleSelectionChange(val) {
			let tagStack = {};
			let deployType;
			if (val) {
				val.forEach(item => {
					deployType = item.deployType;
					if (item.data) {
						this.dataTransform(item.data).map(i => {
							if (!tagStack[i.tag]) {
								tagStack[i.tag] = {
									tag: i.tag,
									services: i.services,
									id: item.id,
								};
							} else {
								const oldList = tagStack[i.tag].services;

								tagStack[i.tag].services = uniqBy([...oldList, ...i.services], 'name');
							}
						});
					}
				});
				this.multipleSelection = this.filterServices(tagStack);
			} else {
				this.multipleSelection = val;
			}
			this.$emit('handleSelectionChange', {
				deployType,
				data: Object.values(this.multipleSelection) ?? [],
			});
		},
		/** 查询列表 */
		async getList() {
			if (this.timer) {
				clearTimeout(this.timer);
				this.timer = null;
			}
			this.timer = setTimeout(async () => {
				try {
					this.loading = true;
					const { data } = await piplineExecPage({
						env: this.env,
						deployId: this.deployId,
						...this.queryParams,
					});
					this.list = data.list ?? [];
					this.total = data.total;
					this.list?.forEach(item => {
						if (!Object.prototype.hasOwnProperty.call(this.envSelectValues, item.id)) {
							this.envSelectValues = Object.assign({}, this.envSelectValues, {
								[item.id]: [],
							});
						}
					});
				} finally {
					this.loading = false;
				}
			}, 300);
		},
		getAlert(title, content, callback) {
			this.$alert(content, title, {
				distinguishCancelAndClose: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				showCancelButton: true,
				callback,
			});
		},
		filterServices(input) {
			// 1. 按 id 降序排序，优先处理大的 id
			const sortedEntries = Object.entries(input).sort((a, b) => b[1].id - a[1].id);

			const result = {};
			const serviceMaxIdMap = new Map(); // 记录每个 service.name 对应的最大 id

			for (const [key, value] of sortedEntries) {
				const currentId = value.id;

				// 2. 过滤掉已经被更大 id 包含的 service.name
				const filteredServices = value.services.filter(service => {
					const maxId = serviceMaxIdMap.get(service.name);
					if (maxId !== undefined && maxId > currentId) {
						return false; // 如果已有更大的 id 包含该 service，则过滤掉
					}
					serviceMaxIdMap.set(service.name, currentId); // 更新最大 id
					return true;
				});

				// 3. 如果仍有 services，则加入结果
				if (filteredServices.length > 0) {
					result[key] = {
						...value,
						services: filteredServices,
					};
				}
			}

			return result;
		},
	},
};
</script>

<style lang="scss" scoped>
.pipeline-execution {
	padding: 16px 10px;
}

.env-select,
:deep(.el-input__inner) {
	height: 32px;
}

.column-services {
	text-align: center;

	.popover-reference {
		cursor: pointer;
		margin: 0 auto 5px;
		width: 80px;
		height: 28px;
		line-height: 28px;
		text-align: center;
		color: #1890ff;

		&:hover {
			opacity: 0.8;
		}
	}
	&-item {
		max-height: 300px;
		overflow-y: auto;
	}
}
</style>
